package ${groupId}.service.security.credential;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import ${groupId}.service.security.authc.MallUsernamePasswordToken;


/**
 * Created by h.p on 2018/12/4.
 * 重试次数限定匹配验证器
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher{

    private final String cacheName = "passwordRetryCache";
    private Cache<String, AtomicInteger> passwordRetryCache;

    /**
     * 初始化密码缓存
     * @param cacheManager
     */
    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache(cacheName);
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        MallUsernamePasswordToken mallToken = (MallUsernamePasswordToken) token;
        String username = mallToken.getUsername();
        String cacheKey = username;
        /* 错误次数累加 1分钟后清除 */
        AtomicInteger retryCount = passwordRetryCache.get(cacheKey);
        if(retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(cacheKey, retryCount);
        }
        if(retryCount.incrementAndGet() > 5) {
            /* 规定时间内超出错误次数 */
            throw new ExcessiveAttemptsException();
        }

        boolean matches = super.doCredentialsMatch(token, info);
        if(matches) {
            passwordRetryCache.remove(cacheKey);
        }
        return matches;
    }

}
